package com.cyy.admin.controller;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.*;

import com.alibaba.fastjson.JSON;
import com.cyy.admin.entity.SysRoleEntity;
import com.cyy.admin.service.SysMenuService;
import com.cyy.admin.service.SysRoleService;
import com.cyy.admin.service.SysSystemlogService;
import com.cyy.base.util.JwtUtils;
import com.cyy.common.MenuItem;
import com.cyy.util.RequestUtil;
import io.jsonwebtoken.Claims;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;
import com.cyy.admin.entity.CyyUserEntity;
import com.cyy.admin.service.CyyUserService;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

/**
 * 系统用户表
 *
 * @author chenyuyi
 * @date 2021-12-01 16:43:08
 */
@Api(tags = "admin")
@Controller
@RequestMapping("admin/cyyuser")
public class CyyUserController {

    @Autowired
    private JwtUtils jwtUtils;

    @Autowired
    private CyyUserService cyyUserService;

    @Autowired
    private SysRoleService sysRoleService;

    @Autowired
    private BCryptPasswordEncoder bCryptPasswordEncoder;

    @Autowired
    private SysMenuService sysMenuService;

    @Autowired
    private SysSystemlogService sysSystemlogService;

    @Autowired
    private StringRedisTemplate redisTemplate;

    private static final Logger logger = LoggerFactory.getLogger(CyyUserController.class);

    @ApiOperation(value = "新增")
    @PostMapping(value = "insert")
    public Object insert(CyyUserEntity cyyUser){
        return cyyUserService.insert(cyyUser);
    }

    @ApiOperation(value = "根据主键更新")
    @PostMapping(value = "updateByPrimaryKey")
    public int updateByPrimaryKey(CyyUserEntity cyyUser) {
        return cyyUserService.updateByPrimaryKey(cyyUser);
    }

    @ApiOperation(value = "条件查询")
    @GetMapping(value = "select")
    public List<CyyUserEntity> select(CyyUserEntity cyyUser) {
        return cyyUserService.select(cyyUser);
    }

    /**
     * 后台登录页面跳转
     * @return
     */
    /**
     * 用户登录
     */
    @RequestMapping(value= "/loginBegin",method = RequestMethod.GET)
    public String loginAfter(HttpServletRequest request) throws UnsupportedEncodingException {
      String errorMsg = request.getParameter("errorMsg");
      if(StringUtils.isNotBlank(errorMsg)){
          request.setAttribute("errorMsg",errorMsg);
      }
      return "system/login";
    }


    /**
     * 后台登录
     * @return
     * @throws Exception
     */
    /**
     * 用户登录
     */
    @RequestMapping(value= "/login",method = RequestMethod.POST)
    public String login(@RequestParam("loginname")String loginname, @RequestParam("password")String password,HttpServletRequest request){
        logger.info("starting login");
        StringBuffer errorMsg = null;
        if (StringUtils.isBlank(loginname) || StringUtils.isBlank(password)){
            errorMsg.append("账户和密码不能为空!");
            request.setAttribute("errorMsg",errorMsg.toString());
            return "redirect:/admin/cyyuser/loginBegin";
        }
        CyyUserEntity user = cyyUserService.findByLoginnameAndPassword(loginname,password);
        if(user != null){
            Map<String,String> infoMap = new HashMap<>();
            String token = jwtUtils.createJwt(user.getUserId(),"user",user.getUserName());
            infoMap.put("token",token);
            infoMap.put("nickname",user.getUserName());//昵称
            infoMap.put("avatar",user.getAvatar());//头像
            request.setAttribute("errorMsg",infoMap);
            if (request.getAttribute("user_claims") != null ) {
                return "redirect:/admin/cyyuser/home";
            }
            logger.info("用户登录:{}", user.getUserName());
            //存入redis
            redisTemplate.opsForValue().set("user", JSON.toJSONString(user));
            RequestUtil.getSession().setAttribute("Authorization","Bear "+ token);
            SysRoleEntity role = sysRoleService.selectById(user.getRoleId());
            if(role != null){
                //用户首页显示
                user.setRoleName(role.getRoleName());
            }
            //用户可访问的菜单写入request
            Collection<MenuItem> userMenus = sysMenuService.loadMenusByRoleId(user.getRoleId());
            request.setAttribute("userMenus", userMenus);
            try {
                //记录登录日志
                sysSystemlogService.saveLoginLog(user,"login");
            } catch (Exception ex) {
                ex.printStackTrace();
            }
            return "redirect:/admin/cyyuser/home";
        }else{
            return "redirect:/admin/cyyuser/loginBegin?errorMsg="+ URLEncoder.encode("手机账号或密码错误");
        }
    }

    @RequestMapping("home")
    public String home(HttpServletRequest request) {
        //未登录跳转到登录页面
       if(request.getAttribute("user_claims") == null){
           return "redirect:/admin/cyyuser/loginBegin";
       }
       //获取当前登录用户
       CyyUserEntity cyyUser = cyyUserService.getLoginUser((Claims)request.getAttribute("user_claims"));
        if(cyyUser == null){
            return "redirect:/admin/cyyuser/loginBegin";
        }
        return "system/home";

    }
}